﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Phoenix.ReflectionExtensions;

namespace PServiceBus.Core.Runtime.Transports {
    public static class TransportHandlers {
        static List<object> _handlers = new List<object>();
        static object _lockObject = new object();
        /// <summary>
        /// Add handler to collection of handler that can be collectively shutdown.
        /// Do not call this method
        /// </summary>
        /// <param name="handler"></param>
        public static void AddHandler(object handler) {
            lock (_lockObject)
                _handlers.Add(handler);
        }
        /// <summary>
        /// Stop all handlers
        /// </summary>
        public static void ShutDown() {
            foreach (var handler in _handlers) 
                ShutDown(handler);
            _handlers.Clear();
        }

        public static void ShutDown(object handler) {
            if (handler == null) return;
            var type = handler.GetType();
            var stopMethod = type.GetMethodEx("Stop");
            if (stopMethod == null) return;
            var stopAction = stopMethod.Get<Action<object>>();
            var isRunningProp = type.GetPropertyEx("IsRunning");
            if (isRunningProp == null) return;
            var isRunning = isRunningProp.GetValueEx<bool>(handler);
            if (isRunning) stopAction(handler);
        }
    }
}
